from sqlalchemy.orm import Session
from models.models import LearnMindMap
from schemas.mindMap import MindMapCreate, MindMapUpdate

def get_mind_map(db: Session, mind_map_id: int):
    return db.query(LearnMindMap).filter(LearnMindMap.id == mind_map_id).first()

def get_mind_maps_by_user(db: Session, user_id: int):
    return db.query(LearnMindMap).filter(LearnMindMap.user_id == user_id).all()

def get_mind_maps_by_material(db: Session, material_id: int,user_id:int):
    return db.query(LearnMindMap).filter(LearnMindMap.material_id == material_id,LearnMindMap.user_id == user_id).all()

def create_mind_map(db: Session, mind_map: MindMapCreate):
    db_mind_map = LearnMindMap(**mind_map.dict())
    db.add(db_mind_map)
    db.commit()
    db.refresh(db_mind_map)
    return db_mind_map

def update_mind_map(db: Session, mind_map_id: int, mind_map: MindMapUpdate):
    """更新思维导图"""
    try:
        db_mind_map = get_mind_map(db, mind_map_id)
        if not db_mind_map:
            raise Exception(f"思维导图ID {mind_map_id} 不存在")

        # 直接更新 JSON 字段
        if mind_map.mind_map_json is not None:
            print(f"更新思维导图: {mind_map.mind_map_json}")
            db_mind_map.mind_map_json = mind_map.mind_map_json
            db_mind_map.version += 1
            
            db.commit()
            db.refresh(db_mind_map)
            print(f"思维导图 {mind_map_id} 更新成功")
        else:
           raise Exception("没有提供新的 mind_map_json 数据")
            
        return db_mind_map

    except Exception as e:
        db.rollback()
        print(f"更新思维导图时发生错误: {str(e)}")
        raise

def delete_mind_map(db: Session, mind_map_id: int):
    db_mind_map = get_mind_map(db, mind_map_id)
    if db_mind_map:
        db.delete(db_mind_map)
        db.commit()
    return db_mind_map
